package com.uwlaser.webservice.client;

import com.predic8.wsdl.Definitions;
import com.predic8.wsdl.WSDLParser;
import com.predic8.wstool.creator.RequestTemplateCreator;
import com.predic8.wstool.creator.SOARequestCreator;
import com.uwlaser.webservice.exception.WebServiceCodeErrorException;
import groovy.xml.MarkupBuilder;
import lombok.Data;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author QZK
 * @Description WSDL实体
 * @Date 2022-11-23-15:04
 * @Version 1.0
 */
@Data
public class WsdlEntity {
    /**
     * wsdl文档地址
     */
    private String url;

    /**
     * wsdl文档对象
     */
    private Definitions wsdl;

    /**
     * 构造器
     */
    private SOARequestCreator creator;

    /**
     * 缓存
     */
    private StringWriter writer = new StringWriter();

    /**
     * 方法列表
     */
    private List<WsdlMethodEntity> methods = new ArrayList<>();

    public WsdlEntity(String url) {
        this.url = url;
        //wsdl文档
        this.wsdl = new WSDLParser().parse(url);
        //构建
        this.creator = new SOARequestCreator(this.wsdl, new RequestTemplateCreator(), new MarkupBuilder(this.writer));
    }

    /**
     * 根据方法名称获取方法实体
     * @param methodName
     * @return
     */
    public WsdlMethodEntity getMethodEntity(String methodName) throws Exception {
        WsdlMethodEntity entity = null;
        for (WsdlMethodEntity method : this.getMethods()) {
            if(method.getMethodName().equals(methodName)){
                entity = method;
                break;
            }
        }
        if(entity == null){
            throw new WebServiceCodeErrorException("方法名称【" + methodName + "】输入有误，无法在模板中找到对应的方法实体！");
        }
        return entity;
    }
}
